package edu.ucsd.cs110.mycity;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

import edu.ucsd.cs110.mycity.controller.ChatController;
import edu.ucsd.cs110.mycity.controller.XMPPController;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class BuddyListActivity extends ListActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_buddy_list);
		refreshBuddies();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_buddy_list, menu);
		return true;
	}
	
	@SuppressLint("NewApi")
	public void refreshBuddies() {
		XMPPController.refreshBuddies();
		Iterator<HashMap<String, String>> iter = XMPPController.getRosterMap().iterator();
		while (iter.hasNext()) {
			HashMap<String,String> h = iter.next();
			Log.i("Listing roster" , h.get("username"));
			Log.i("Listing roster", h.get("presence"));
		}
		SimpleAdapter adapt = new SimpleAdapter(this, XMPPController.getRosterMap(), R.layout.buddylistitem, new String[] { "username", "presence" }, new int[] { R.id.useremail, R.id.presence });
		this.setListAdapter(adapt);
	}
	
	@Override
    protected void onListItemClick(ListView l,  View view, int position, long id) {
	  Collection<String> roster = XMPPController.getBuddies();
	  Object[] users = roster.toArray();
	  ChatController.doChat(this, (String) users[position]);
      super.onListItemClick(l, view, position, id);
    }	
	
	@Override
	protected void onPause() {
		MyCity.pause();
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		MyCity.resume();
		super.onResume();
	}
	
	@Override
	public void onBackPressed() {
		Intent i = new Intent(this,MyCityMapActivity.class);
		i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		this.startActivity(i);
		super.onBackPressed();
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.map) {
			Intent mapIntent = new Intent(BuddyListActivity.this,MyCityMapActivity.class);
			mapIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			this.startActivity(mapIntent);
			return true;
		}
		Log.e("Menu","menu didn't work");
		return super.onOptionsItemSelected(item);
	}
}
